import 'dart:async';

import 'package:baselib/base/base_responce.dart';
import 'package:baselib/util/common_apiservice.dart';
import 'package:baselib/util/common_utils.dart';
import 'package:baselib/util/shared_preferences_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/model/html_bean.dart';
import 'package:flutter_app/model/login_bean.dart';
import 'package:flutter_app/model/qrcode_bean.dart';
import 'package:flutter_app/model/scan_result.dart';
import 'package:flutter_app/util/colours.dart';
import 'package:flutter_app/util/urls.dart';
import 'package:flutter_app/widget/complete_dialog.dart';
import 'package:flutter_app/widget/contanct_widget.dart';
import 'package:flutter_app/widget/forget_pass.dart';
import 'package:flutter_app/widget/login_dialog.dart';
import 'package:flutter_app/widget/wx_login_dialog.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:super_tooltip/super_tooltip.dart';
import 'package:toast/toast.dart';
import 'package:baselib/util/commonponet.dart' as rxdart;
class SpalshController extends GetxController{

  static SpalshController get to => Get.find();

  var isPhonePasswordLogin=true.obs;
  var userName="".obs;
  var userPassWord="".obs;
  var showPassWord = true.obs;
  var userPhone="".obs;
  var userSmsCode="".obs;
  var userCompany="".obs;

  var loginPassErrortext="账号不能为空"?.obs;
  var loginPassWordErrortext="密码不能为空"?.obs;

  var loginSmsErrortext="手机号不能为空"?.obs;
  var loginSmsPassWordErrortext="密码不能为空"?.obs;

  var loginCompanyErrortext="公司不能为空"?.obs;

  var isLogin =  SharedPreferencesUtils().getToken().isNotEmpty.obs;
  var loginBean=LoginBean().obs;
  var userLoginname=SharedPreferencesUtils().getUserName().obs;

  var isKnown=false.obs;

  var htmlData="".obs;

  var qrcodeBean=QrcodeBean().obs;

  var iswxExpire=false.obs;

  var tabIndex=0.obs;

  var personType=0.obs;//0不展示 1个人中心 2交易记录 3账单管理 4待核销 5优惠券
  final maps=["个人中心", "交易记录", "账单管理","待核销金额","优惠券"];



  String getTitle(){
    if(personType.value==1) return "首页";
    else if(personType.value==2) return "交易记录";
    else if(personType.value==3) return "账单管理";
    else if(personType.value==4) return "待核销金额";
    else if(personType.value==5) return "优惠券";
    else return "";
  }



  ///客服联系方式
  void showKefuDialog(BuildContext context){
    var overlayState = Overlay.of(context);
    OverlayEntry overlayEntry = new OverlayEntry(
        builder: (context1) {
          return Align(
            alignment: Alignment.bottomRight,
            child: Container(
              height: 300,
              child: Column(
                children: [
                  ContanctPage(),
                  Container(
                    width: 80,
                    color: ColourRes.app_265385,
                    child: Column(
                      children: [
                        SizedBox(
                          height: 5,
                        ),
                        Image.asset(
                          CommonUtils.getImgPath("kefu.png"),
                          width: 24,
                        ),
                        SizedBox(
                          height: 10,
                        ),
                        Text("微信公众号",
                            style: TextStyle(color: Colors.white)),
                        SizedBox(
                          height: 5,
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          );
        });
    overlayState.insert(overlayEntry);
  }


  ///登录弹框
  Widget buildLoginDialog() =>Dialog(
    backgroundColor:Colors.white,
    elevation:5,
    shape:RoundedRectangleBorder(
      borderRadius:BorderRadius.all(Radius.circular(10))
    ),
    child:Container(
      width:480,
      height: 460,
      child: loginDialog(),
    ),);


  ///完善信息dialog
  Widget buildCompleteDialog(String uuid) =>Dialog(
    backgroundColor:Colors.white,
    elevation:5,
    shape:RoundedRectangleBorder(
        borderRadius:BorderRadius.all(Radius.circular(10))
    ),
    child:Container(
      width:480,
      height: 500,
      child: CompleteDialog(uuid),
    ),);


   double getWidgetGlobalRect(GlobalKey key) {
    RenderBox renderBox = key.currentContext.findRenderObject();
    var offset = renderBox.localToGlobal(Offset.zero);
    return offset.dx;
  }

  ///微信扫码弹框
  Widget buildWxDialog() =>Dialog(
    backgroundColor:Colors.white,
    elevation:5,
    shape:RoundedRectangleBorder(
        borderRadius:BorderRadius.all(Radius.circular(10))
    ),
    child:Container(
      width:480,
      height: 460,
      child: WxDialog(),
    ),);

  ///忘记密码弹框
  Widget buildForgetpassDialog() =>Dialog(
    backgroundColor:Colors.white,
    elevation:5,
    shape:RoundedRectangleBorder(
        borderRadius:BorderRadius.all(Radius.circular(10))
    ),
    child:Container(
      width:480,
      height: 460,
      child: forgetPassDialog(),
    ),);

  ///倒计时
  Timer _timer;
  var start = 120.obs;
  bool isbegin = false;
  void timer() {
    if (isbegin) return;
    const oneSec = const Duration(seconds: 1); //间隔1秒
    _timer = new Timer.periodic(oneSec, (timer) {
      if (start < 1) {
        //如果小于1则停止倒计时
        start.value = 120;
        isbegin = false;
        timer.cancel();
      } else {
        isbegin = true;
        start = start - 1; //自减一
      }
    });
  }

  //密码登录
  Future<void> loginByPass(BuildContext context) async{

    if(!isKnown.value){
      Toast.show("请阅读并同意《易车车用户协议》", context, duration: Toast.LENGTH_LONG, gravity:  Toast.TOP,backgroundColor:Colors.red);
      return;
    }

    if(isPhonePasswordLogin.value) {///账号登录
      if (userName.isEmpty) {
        loginPassErrortext.value = "账号不能为空";
        return;
      }
      if (userPassWord.isEmpty) {
        loginPassWordErrortext.value = "密码不能为空";
        return;
      }

      var body = {
        'username': userName.value,
        'password': userPassWord.value
      };
      BaseResponce responce = await CommonApiService.requestPost(
          Get.context,
          url: Urls.login,
          data: body
      );
      if(responce.code==200){
        LoginBean data=LoginBean.fromJson(responce.data);
        Get.back();
        SharedPreferencesUtils().saveToken(data.accessToken);
        SharedPreferencesUtils().saveUsername(data.username);
        loginBean.value=data;
        isLogin.value=true;
        userLoginname.value=data.username;
      }else{
        print(responce.message);
        Toast.show(responce.message, context, duration: Toast.LENGTH_SHORT, gravity:  Toast.TOP,backgroundColor:Colors.red);
        //  ScaffoldMessenger.of(context).showSnackBar(_buildSnackBar(responce.message));
      }

    }else{///验证码登录
      if (userPhone.isEmpty) {
        loginSmsErrortext.value = "手机号不能为空";
        return;
      }
      if (userSmsCode.isEmpty) {
        loginSmsPassWordErrortext.value = "验证码不能为空";
        return;
      }

      var body = {
        'tel': userPhone.value,
        'smscode': userSmsCode.value,
      };
      BaseResponce responce = await CommonApiService.requestPost(
          Get.context,
          url: Urls.sms_login,
          data: body
      );
      if(responce.code==200){
        LoginBean data=LoginBean.fromJson(responce.data);
        Get.back();
        SharedPreferencesUtils().saveToken(data.accessToken);
        SharedPreferencesUtils().saveUsername(data.username);
        loginBean.value=data;
        isLogin.value=true;
        userLoginname.value=data.username;
      }else{
        Toast.show(responce.message, context, duration: Toast.LENGTH_LONG, gravity:  Toast.TOP,backgroundColor:Colors.red);
      }
    }
  }


  ///完善信息登录
  Future<void> completeInfo(BuildContext context,String uuid) async{
    if (userPhone.isEmpty) {
      loginSmsErrortext.value = "手机号不能为空";
      return;
    }
    if (userSmsCode.isEmpty) {
      loginSmsPassWordErrortext.value = "验证码不能为空";
      return;
    }
    if (userCompany.isEmpty) {
      loginCompanyErrortext.value = "公司不能为空";
      return;
    }

    var body = {
      'tel': userPhone.value,
      'smscode': userSmsCode.value,
      'union_id':uuid,
      'company_name':userCompany.value
    };
    BaseResponce responce = await CommonApiService.requestPost(
        Get.context,
        url: Urls.sms_login,
        data: body
    );
    if(responce.code==200){
      LoginBean data=LoginBean.fromJson(responce.data);
      Get.back();
      SharedPreferencesUtils().saveToken(data.accessToken);
      SharedPreferencesUtils().saveUsername(data.username);
      loginBean.value=data;
      isLogin.value=true;
      userLoginname.value=data.username;
    }else{
      Toast.show(responce.message, context, duration: Toast.LENGTH_LONG, gravity:  Toast.TOP,backgroundColor:Colors.red);
    }
  }

  ///获取验证码
  Future<void> getSmsCode(BuildContext context) async{

    if (userPhone.isEmpty) {
      loginSmsErrortext.value = "手机号不能为空";
      return;
    }

    var body = {
      'tel': userPhone.value,
    };
    BaseResponce responce = await CommonApiService.requestGet(
        Get.context,
        url: Urls.send_sms,
        data: body
    );
    if(responce.code==200){
      Toast.show(responce.message, context, duration: Toast.LENGTH_LONG, gravity:  Toast.TOP,backgroundColor:Colors.red);
      timer();
    }else{
      Toast.show(responce.message, context, duration: Toast.LENGTH_LONG, gravity:  Toast.TOP,backgroundColor:Colors.red);
    }
  }

  ///获取用户协议
  Future<void> getXieyi(BuildContext context) async{
    BaseResponce responce = await CommonApiService.requestGet(
        Get.context,
        url: Urls.privacyurl,
    );
    if(responce.code==200){
      HtmlBean data=HtmlBean.fromJson(responce.data);
      htmlData.value=data.content;
    }else{
      Toast.show(responce.message, context, duration: Toast.LENGTH_LONG, gravity:  Toast.TOP,backgroundColor:Colors.red);
    }
  }

  ///退出登录
  Future<void> loginOut(BuildContext context) async{
    BaseResponce responce = await CommonApiService.requestGet(
      Get.context,
      url: Urls.logout,
    );
    if(responce.code==200||responce.code==4002){
      SharedPreferencesUtils().saveToken("");
      SharedPreferencesUtils().saveUsername("");
      isLogin.value=false;
      userLoginname.value="";
    }
    else {
      Toast.show(responce.message, context, duration: Toast.LENGTH_LONG, gravity:  Toast.TOP,backgroundColor:Colors.red);
    }
  }


  ///获取微信二维码
  Future<void> getQrcode(BuildContext context) async{

    BaseResponce responce = await CommonApiService.requestPost(
      Get.context,
      url: Urls.loginQrcode,
    );
    if(responce.code==200){
      QrcodeBean data=QrcodeBean.fromJson(responce.data);
      qrcodeBean.value=data;
      iswxExpire.value=false;
      qrTimer(data.expire,data.uuid,context);
      rxdart.Rx.timer(1, new Duration(seconds: data.expire)).listen((event) {
        iswxExpire.value=true;
        cancelQrTimer();
      });
    }else{
      Toast.show(responce.message, context, duration: Toast.LENGTH_LONG, gravity:  Toast.TOP,backgroundColor:Colors.red);
    }
  }


  ///倒计时
  Timer qrtimer;
  void qrTimer(int expire,String uuid,BuildContext context) {
    const oneSec = const Duration(seconds: 3); //间隔1秒
    qrtimer = new Timer.periodic(oneSec, (timer) {
      getQrcodeResult(uuid,context);
    });
  }

  ///获取扫码结果
  Future<void> getQrcodeResult(String uuid,BuildContext context) async{
    var body = {
      'uuid': uuid,
    };
    BaseResponce responce = await CommonApiService.requestPost(
      Get.context,
      url: Urls.get_qrcode_result,
      data: body
    );
    if(responce.code==200){
      ScanResult data=ScanResult.fromJson(responce.data);
      if(data!=null){
        qrtimer?.cancel();
        if(data.status==2){
          // 2 登录成功
          Get.back();
          SharedPreferencesUtils().saveToken(data.data.accessToken);
          SharedPreferencesUtils().saveUsername(data.data.username);
          loginBean.value=data.data;
          isLogin.value=true;
          userLoginname.value=data.data.username;
        }else if(data.status==1){
          //1 新用户
          Get.back();
          showDialog(context: context,barrierDismissible:false,
              builder: (ctx)=>buildCompleteDialog(uuid));
        }
      }
    }else{
      //Toast.show(responce.message, context, duration: Toast.LENGTH_LONG, gravity:  Toast.TOP,backgroundColor:Colors.red);
    }
  }

  ///取消轮询
  void cancelQrTimer(){
    qrtimer?.cancel();
  }

  Widget _buildSnackBar(String msg) {
    return SnackBar(
      elevation: 3,
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(10), topRight: Radius.circular(10))),
      content: Text(msg),
      duration: Duration(seconds: 3),
      //持续时间
      backgroundColor: Colors.red,
      onVisible: () => print('onVisible'),
      action: SnackBarAction(
          textColor: Colors.white, label: '确定', onPressed: () {}),
    );
  }
}

